package com.lkm.app_ui.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

import com.google.gson.annotations.SerializedName;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.help.TaskHelp;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.netapi.AppApi;
import com.lkm.app_ui.view.choiceCard.ChoiceCard;
import com.lkm.app_ui.view.choiceCard.ChoiceItem;
import com.lkm.app_ui.view.choiceCard.IChoiceItem;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.util.CycleHelp;
import com.lkm.market2_0.entity.BreedTo;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.m.steelyardserver.GoodsButtonInfoTo;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardserver.SteelyardServerModule;
import com.lkm.market2_0.m_imple.steelyardserver.server.AbsSendWriteTask;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;



public class GoodsButtonFragment extends MBaseFragment implements ChoiceCard.ChoiceCardBC {


    @Override
    protected boolean configIsLockKey() {
        return true;
    }

    public static GoodsButtonFragment getInstance() {
        GoodsButtonFragment f = new GoodsButtonFragment();
        Bundle data = new Bundle();

        f.setArguments(data);

        return f;
    }


    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_goodsbutton;
    }

    private ChoiceCard mChoiceCard;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mChoiceCard = findViewById(R.id.ChoiceCard);

        mChoiceCard.init(false, R.layout.view_choice_card, R.layout.item_fun_mini_p, R.layout.item_fun_mini, 6);

        mChoiceCard.setChoiceCardBC(this);

        getClassTask();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        reOnKeyEvent();
        reOnKeyNumberEvent();
    }


    private void reOnKeyEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {
                if (!data.isIntercepted()) {
                    data.setIntercepted(true);
                    if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
                        RouterUINavigation.getInstance().dismiss(GoodsButtonFragment.this);
                    }
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    private void reOnKeyNumberEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnKeyNumberEvent>() {
            @Override
            public Class<OnKeyNumberEvent> getBusEventClass() {
                return OnKeyNumberEvent.class;
            }

            boolean isOnce = false;
            @Override
            public void onReceiver(OnKeyNumberEvent data) {
                if (isExit()) return;


                if (!data.isIntercepted()) {
                    data.setIntercepted(true);
                    if(!isOnce&&data.isFinally()){

                        isOnce = true;
                        return;
                    }
                    isOnce = true;

                    if (data.isFinally()) {
                        mChoiceCard.onItemClick( ""+((int) data.getNumber()));
//                        wifiFragmentFun.onNumber(data.getNumber());
                    }
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }





    private void syncGoodsButtonToSteelyard(String steelyardMac, List<BreedTo> breedTos) {

        if (isExit()) return;

        List<GoodsButtonInfoTo> goodsButtonInfoTos = new ArrayList<>(breedTos.size());

        for (BreedTo b : breedTos) {
            GoodsButtonInfoTo goodsButtonInfoTo = new GoodsButtonInfoTo(b.goods_name, b.price);
            goodsButtonInfoTos.add(goodsButtonInfoTo);
        }

        try {
            SteelyardServerModule steelyardServerModule = AppConst.getModuleManager().loadModule(SteelyardServerModule.class);
            AbsSendWriteTask absSendWriteTask = steelyardServerModule.setGoodsButton(steelyardMac, goodsButtonInfoTos);
            absSendWriteTask.addBackCall(new BackCallAdapter<Void, Boolean>() {
                @Override
                protected void onEnd(com.lkm.frame.task2.Task<?, Void, Boolean> task, Boolean aBoolean, boolean isCancel) {
                    super.onEnd(task, aBoolean, isCancel);
                    if (isExit()) return;

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ViewUIHelp.disProgressBar("loadBreedForSTask1");
                            if (!isCancel && aBoolean) {
                                AppUIHelp.tryShowTipsSHORT( "同步商品信息成功");
                                RouterUINavigation.getInstance().dismiss(GoodsButtonFragment.this);
                            } else {
                                AppUIHelp.tryShowTipsSHORT( "同步商品信息异常");
                            }
                        }
                    });


                }
            });
            ViewUIHelp.showProgressBar(getActivity(), "同步商品信息到称体", "loadBreedForSTask1");
        } catch (Exception e) {
            AppUIHelp.tryShowTipsSHORT( "同步商品信息异常");

        }
    }




    @Override
    public void onChoiceChangeListener(ChoiceCard cc, IChoiceItem c, int index) {
        if (c.getIsChoice()) {
            GoodsClassTo goodsClassTo = (GoodsClassTo) c.getTag();
            getButtonsTask(goodsClassTo);
        }
    }


    private void getClassTask() {
        if (isExit()) return;
        TaskHelp.cancelById(GetClassTask.class.getName());
        Task task = new GetClassTask();
        task.action();
        task.setParam(null);
        task.execTask();

    }

    private void initClass(List<GoodsClassTo> goodsClassTos) {
        if (goodsClassTos == null) return;
        ChoiceItem[] cis = new ChoiceItem[goodsClassTos.size()];
        int i = 0;
        for (GoodsClassTo funItem : goodsClassTos) {
            cis[i] = new ChoiceItem("" + funItem.id, funItem.id+":"+funItem.name);
            cis[i].setTag(funItem);
            i++;
        }

        mChoiceCard.binData(cis);
    }

    private class GetClassTask extends TaskAdapter<Void, String, ResponEntity<List<GoodsClassTo>>> {



        public GetClassTask() {
            super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), GetClassTask.class.getName(), AppConst.getTaskManager2());
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            ViewUIHelp.showProgressBar(getActivity(), "加载样品类型...", GetClassTask.class.getName());
        }

        @Override
        public void doExecuting(Void param) {
            super.doExecuting(param);
            mTaskExecutor.executor(new Runnable() {
                @Override
                public void run() {
                    ResponEntity<List<GoodsClassTo>> responEntity = ResponEntity.fromJson(AppApi.breed_class(GetClassTask.this), new com.google.gson.reflect.TypeToken<List<GoodsClassTo>>() {
                    }.getType(), "");
                    complete(responEntity);

                }
            });
        }

        @Override
        public void onFinish(ResponEntity<List<GoodsClassTo>> aBoolean) {
            super.onFinish(aBoolean);
            ViewUIHelp.disProgressBar(GetClassTask.class.getName());
            if (aBoolean.isSuccess()) {
                uiTips("加载样品类型成功。");
                initClass(aBoolean.getData());
            } else {
                uiTips("加载样品类型失败。");
            }

        }

        @Override
        public void onCancel() {
            super.onCancel();
            ViewUIHelp.disProgressBar(GetClassTask.class.getName());
        }
    }



    private void getButtonsTask(GoodsClassTo goodsClassTo) {
        if (isExit()) return;
        TaskHelp.cancelById(GetButtonsTask.class.getName());
        Task task = new GetButtonsTask();
        task.action();
        task.setParam(goodsClassTo);
        task.execTask();

    }
    private class GetButtonsTask extends TaskAdapter<GoodsClassTo, String, ResponEntity<List<BreedTo>>> {

        public GetButtonsTask() {
            super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), GetButtonsTask.class.getName(), AppConst.getTaskManager2());
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            ViewUIHelp.showProgressBar(getActivity(), "加载按钮...", GetButtonsTask.class.getName());
        }

        @Override
        public void doExecuting(GoodsClassTo param) {
            super.doExecuting(param);
            mTaskExecutor.executor(new Runnable() {
                @Override
                public void run() {
                    ResponEntity<List<BreedTo>> responEntity = ResponEntity.fromJson(AppApi.buttons(param.id,GetButtonsTask.this), new com.google.gson.reflect.TypeToken<List<BreedTo>>() {
                    }.getType(), "");
                    complete(responEntity);






//                            breedTo.bid = goodsTo.bid;
//                            breedTo.id = goodsTo.id;
//                            breedTo.classId = goodsTo.classId;
//                            breedTo.goods_id = goodsTo.goods_id;
//                            breedTo.goods_name = goodsTo.goods_name;
//                            breedTo.price = goodsTo.price;







                }
            });
        }

        @Override
        public boolean onInterceptEnd(boolean isCancel, ResponEntity<List<BreedTo>> result) {
            ViewUIHelp.disProgressBar(GetButtonsTask.class.getName());
            return super.onInterceptEnd(isCancel, result);
        }

        @Override
        public void onFinish(ResponEntity<List<BreedTo>> aBoolean) {
            super.onFinish(aBoolean);
            if (aBoolean.isSuccess()) {
                uiTips("加载按键成功，正在下发到台秤，按钮个数："+aBoolean.getData().size());
                if(RunTimeData.steelyardInfo!=null)
                    syncGoodsButtonToSteelyard(RunTimeData.steelyardInfo.steelyardMac,aBoolean.getData());
            } else {
                uiTips("加载按键失败。");
            }

        }
    }


    public void uiTips(final String s) {
        if (isExit()) return;
        final Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AppUIHelp.tryShowTipsSHORT(  s);
                }
            });
        }
    }


    private static class GoodsClassTo {

        @SerializedName("id")
        public int id;
        @SerializedName("name")
        public String name;
        @SerializedName("sort_id")
        public int sort_id;
    }

    private static class GoodsTo {



        @SerializedName("id")
        public int id;


        @SerializedName("goods_id")
        public int goods_id;

        @SerializedName("goods_name")
        public String goods_name;


        @SerializedName("breed_id")
        public int bid;

        @SerializedName("class_id")
        public int classId;

        @SerializedName("price")
        public float price;

    }
}//GoodsButtonFragment end